package com.ntd.study.protocol.web_socket;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;



public class UtilWsClient extends WsClient{
    public UtilWsClient(URI serverUri) {
        super(serverUri);
    }
    public static void main(String[] args) throws URISyntaxException, InterruptedException {
        WsClient myClient = new WsClient(new URI("ws://localhost:8029/ws/testWebSocket"));
        myClient.connect();
        // 判断是否连接成功，未成功后面发送消息时会报错
        while (!myClient.getReadyState().equals(ReadyState.OPEN)) {
            System.out.println("连接中···请稍后");
            Thread.sleep(1000);
        }
        myClient.send("MyClient");
        System.out.println("发送成功");
    }
}
class WsClient extends WebSocketClient {
    public WsClient(URI serverUri) {
        super(serverUri);
    }
    @Override
    public void onOpen(ServerHandshake arg0) {
        System.out.println("握手成功");
    }
    @Override
    public void onClose(int arg0, String arg1, boolean arg2) {
        System.out.println("连接关闭");
    }
    @Override
    public void onError(Exception arg0) {
        System.out.println("发生错误");
    }
    @Override
    public void onMessage(String arg0) {
        System.out.println("收到消息" + arg0);
    }
}
